//
//  initialUserInfoStack.swift
//  demo01
//
//  Created by babybus on 2025/7/1.
//
import Foundation
import UIKit
import SnapKit
import Alamofire

class InitialUserInfoStack:UIStackView{
    //全局变量
    private var userImagePath:String = "./1.jpg"
    private var userPhone:UILabel = UILabel()
    private var userImage:UIImageView = UIImageView()
    private var userInfoFromApi:InitialUserInfo?
    private let api = "/initialuserinfo"
    //初始化函数
    override init(frame: CGRect) {
        super.init(frame: frame)

        attributeInit()
        setupUI()
        loadData(userId: 1)
    }
    required init(coder: NSCoder) {
        fatalError("init(coder:NSCoder) -- fatalError")
    }
    //属性设置
    func attributeInit(){
        axis = .horizontal
        alignment = .fill
        distribution = .fill
    }
    //整体布局
    func setupUI(){
        //头像设置
        userImage.layer.cornerRadius = 15
        userImage.layer.masksToBounds = true

        //将头像和标签加入到stack中
        self.addArrangedSubview(userImage)
        self.addArrangedSubview(userPhone)
        
        //组件布局
        userImage.snp.makeConstraints({make in
            make.height.equalToSuperview()
            make.width.equalTo(userImage.snp.height)
        })
    }
    func loadData(userId:Int){
        let url = AllUrl.LH_URL + api + "?userId=\(userId)"
        
        AF.request(url,method: .get)
            .validate(statusCode: 200..<300)
            .responseDecodable(of:InitialUserInfo.self){ response in
                switch response.result{
                case .success(let user):
                    self.userImagePath = user.userImagePath
                    DispatchQueue.main.async {
                        if let image = UIImage(named: self.userImagePath) {
                            self.userImage.image = image
                        }else{
                            self.userImage.image = UIImage(systemName: "person.circle")
                        }
                        self.userPhone.text = user.userPhone
                    }
                case .failure(let error):
                    print("错误: \(error.localizedDescription)")
                }
            }
    }
}
